package com.fany.filesearcher;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteStatement;
import com.fany.utils.FileHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

class SQLiteFileRecordAccessor extends SQLiteOpenHelper
{
    // TableName = "IFileRecorder";
    private int _currentId;
    private static int _recordCount;

    public SQLiteFileRecordAccessor(Context context, String name, SQLiteDatabase.CursorFactory cursorFactory,
                                    int version)
    {
        super(context, name, cursorFactory, version);
    }

    private static final String SqlDefinition_FileRecorder = "create table IFileRecorder("
            + "id integer primary key autoincrement," + "name varchar(255), " + "completed int, " + "path varchar(255)"
            + ")";

    @Override
    public void onCreate(SQLiteDatabase database)
    {
        database.execSQL(SqlDefinition_FileRecorder);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2)
    {
    }

    public List<String> search(String filter, boolean append)
    {
        List<String> results = new ArrayList<String>();
        SQLiteDatabase database = getReadableDatabase();
        try
        {
            String SQL = "select id, path from IFileRecorder where (id > %d) and (name like '%%%s%%') order by id limit 20 ";
            if (!append)
            {
                _currentId = -1;
            }
            SQL = String.format(SQL, _currentId, filter);
            assert database != null;
            Cursor cursor = database.rawQuery(SQL, null);
            while (cursor.moveToNext())
            {
                _currentId = cursor.getInt(0);
                results.add(cursor.getString(1));
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            assert database != null;
            database.close();
        }
        return results;
    }

    public boolean hasLoaded()
    {
        if (_recordCount == 0)
        {
            String SQL = "select count(*) as recordCount from IFileRecorder";
            SQLiteDatabase database = getReadableDatabase();
            Cursor cursor = database.rawQuery(SQL, null);
            cursor.moveToFirst();
            _recordCount = cursor.getInt(0);
        }
        return _recordCount > 0;
    }

    public void deleteDatabase()
    {
        String dbPath = FileHelper.getStoragePath() + File.separator + getDatabaseName();
        File dbFile = new File(dbPath);
        dbFile.delete();
        _recordCount = 0;
    }

    public void clear()
    {
        SQLiteDatabase database = getWritableDatabase();
        try
        {
            _recordCount = 0;
            assert database != null;
            database.delete("IFileRecorder", null, null);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            assert database != null;
            database.close();
        }
    }

    public void insert(List<String> paths)
    {
        SQLiteDatabase database = getWritableDatabase();
        final String SQL = "insert into IFileRecorder (name, path) values(?, ?)";
        try
        {
            database.beginTransaction();
            SQLiteStatement stat = database.compileStatement(SQL);
            for (int i = 0; i < paths.size(); i++)
            {
                stat.bindString(1, FileHelper.extractFileName(paths.get(i)));
                stat.bindString(2, paths.get(i));
                stat.executeInsert();
                _recordCount++;
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            assert database != null;
            database.setTransactionSuccessful();
            database.endTransaction();
            database.close();
        }
    }

    public void delete(String path)
    {
        SQLiteDatabase database = getWritableDatabase();
        try
        {
            assert database != null;
            int affectedRows = database.delete("IFileRecorder", "path like ?", new String[]{path + "%%"});
            _recordCount -= affectedRows;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            assert database != null;
            database.close();
        }
    }

    public int getRecordCount()
    {
        return _recordCount;
    }

}
